import 'package:base/main.dart';
import 'package:flutter/material.dart';
import 'package:framework/main.dart';
import 'package:module_discover/enums/domain_type_enum.dart';
import 'package:module_discover/pages/filter_domain/filter_domain_logic.dart';
import 'package:module_discover/pages/filter_domain/view/choice_item_view.dart';
import 'package:module_discover/pages/filter_domain/widgets/child/child_custom_widget.dart';
import 'package:module_discover/pages/filter_domain/widgets/child/child_input2_widget.dart';
import 'package:module_discover/pages/model/filter_model.dart';
import 'package:module_discover/utils/dis_cons.dart';

class ChildSingleWidget extends StatelessWidget {
  /// 传参
  final BaseFilterItem child;

  /// 取参
  final FilterDomainLogic logic = Get.find<FilterDomainLogic>();

  ChildSingleWidget({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    _initData(child.children);
    return _buildData(child.children);
  }

  _buildData(List<BaseFilterItem> data) {
    if (data == null || data.isEmpty) {
      return SizedBox();
    }
    final type = DomainTypeEnum.fromValue(child.type);
    Widget childWidget = SizedBox();
    return Container(
      padding: const EdgeInsets.only(top: 10),
      child: Obx(() => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Wrap(
                spacing: Constants.px_6,
                runSpacing: Constants.px_10,
                children: List.generate(data.length, (index) {
                  BaseFilterItem item = data[index];

                  /// 是否有子集
                  if (item.children.isNotEmpty &&
                      item.isSelected.value == true) {
                    childWidget = _buildCustomWidget(
                      children: item.children,
                      custom: null,
                    );
                  }

                  if (type == DomainTypeEnum.S_CHOICE) {
                    return ChoiceItemView(
                      text: item.title,
                      isSelected: item.isSelected.value,
                      onTap: () {
                        final currentSelected = item.isSelected.value;
                        String keyName = child.title;

                        /// 域名构成
                        if (child.key == DisCons.TBGCTE) {
                          logic.filterStateVM.getYMGCTECategories(DisCons.TBGC);
                          keyName = DisCons.S_TBGC;
                        } else if (child.key == DisCons.YMGC) {
                          logic.filterStateVM.getYMGCTECategories(DisCons.YMGC);
                          keyName = DisCons.S_YMGC;
                        } else {
                          for (var element in data) {
                            element.isSelected.value = false;
                          }
                        }
                        item.isSelected.value = !currentSelected;

                        /// 不限
                        if (item.key == DisCons.NO_LIMIT) {
                          String parentKey = logic
                              .domainTitles[logic.selectedIndex.value]
                              .value
                              .key;
                          logic.deleteSelectedMap(parentKey, child.key);
                          item.isSelected.value = true;
                          return;
                        }

                        /// 是否选中
                        if (item.isSelected.value) {
                          /// 有子集
                          if (item.children.isNotEmpty) {
                            String parentKey = logic
                                .domainTitles[logic.selectedIndex.value]
                                .value
                                .key;
                            // 删除数据
                            logic.deleteSelectedMap(parentKey, child.key);
                            // 删除input的值
                            for (var item in item.children) {
                              logic.selectInputVM
                                  .getController("${item.key}1")
                                  .text = "";
                              logic.selectInputVM
                                  .getController("${item.key}2")
                                  .text = "";
                            }
                            item.isSelected.value = true;
                          }
                          if (child.custom != null) {
                            logic.selectInputVM
                                .getController("${child.custom?.key}_1")
                                .text = "";
                            logic.selectInputVM
                                .getController("${child.custom?.key}_2")
                                .text = "";
                          }
                          logic.addSelectMaps(
                              childKey: child.key,
                              sChoice: true,
                              isSelected: item.isSelected.value,
                              name: keyName,
                              key: item.key,
                              value: item.value);
                        } else {
                          String parentKey = logic
                              .domainTitles[logic.selectedIndex.value]
                              .value
                              .key;
                          logic.deleteSelectedMap(parentKey, child.key);
                        }
                      },
                      selectedColor: Colors.red[50],
                      unselectedColor: JColor.color_f3f3f3,
                      borderColor: Colors.red[300],
                    );
                  } else if (type == DomainTypeEnum.M_CHOICE) {
                    return ChoiceItemView(
                      text: item.key,
                      isSelected: item.isSelected.value,
                      onTap: () {
                        item.toggleSelection();
                        if (item.key == DisCons.NO_LIMIT) {
                          String parentKey = logic
                              .domainTitles[logic.selectedIndex.value]
                              .value
                              .key;
                          logic.deleteSelectedMap(parentKey, child.key);
                          item.isSelected.value = true;
                          return;
                        } else {
                          for (var element in data) {
                            if (element.key == DisCons.NO_LIMIT) {
                              element.isSelected.value = false;
                            }
                          }
                          logic.addSelectMaps(
                              childKey: child.key,
                              sChoice: false,
                              isSelected: item.isSelected.value,
                              name: child.title,
                              key: item.key,
                              value: item.value);
                        }
                      },
                      selectedColor: Colors.red[50],
                      unselectedColor: JColor.color_f3f3f3,
                      borderColor: Colors.red[300],
                    );
                  } else {
                    return SizedBox();
                  }
                }),
              ),
              childWidget,
              child.custom != null
                  ? ChildCustomWidget(child: child)
                  : SizedBox()
            ],
          )),
    );
  }

  Widget _buildCustomWidget(
      {required List<BaseFilterItem> children, required custom}) {
    return SingleChildScrollView(
      child: Column(
        children: children.map((item) => _buildOptionView(item)).toList(),
      ),
    );
  }

  Widget _buildOptionView(BaseFilterItem item) {
    final type = DomainTypeEnum.fromValue(item.type);
    switch (type) {
      case DomainTypeEnum.INPUT2:
        return _buildInput2Widget(item);
      case DomainTypeEnum.M_CHOICE:
        return _buildMChoiceItemView(item);
      case DomainTypeEnum.S_CHOICE:
        return _buildMChoiceItemView(item);
      default:
        Log.d('ChildCustomWidget _buildOptionView type = $type');
    }
    return SizedBox();
  }

  _buildMChoiceItemView(BaseFilterItem item) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(height: Constants.spaceBase),
          Text(
            item.title,
            style: TextStyle(
              fontSize: 13,
              color: Colors.black,
              fontWeight: FontWeight.bold,
            ),
          ),
          _buildChildMChoiceWidget(item),
          SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildInput2Widget(BaseFilterItem item) {
    return ChildInput2Widget(
      name: item.title,
      logic: logic,
      fieldKey1: "${item.key}_1",
      onChanged1: (v) {
        _onChanged(item);
      },
      fieldKey2: "${item.key}_2",
      onChanged2: (v) {
        _onChanged(item);
      },
    );
  }

  _onChanged(BaseFilterItem item) {
    String parentKey = logic.domainTitles[logic.selectedIndex.value].value.key;
    final jznl_1 = logic.selectInputVM.getController("${item.key}_1").text;
    final jznl_2 = logic.selectInputVM.getController("${item.key}_2").text;
    if (jznl_1.isNotEmpty && jznl_2.isNotEmpty) {
      logic.filterPreviewVM.setSelectedMaps(DomainTypeEnum.INPUT2, item.title,
          parentKey, "${item.key}_1", item.title, jznl_1,
          isShow: false);
      logic.filterPreviewVM.setSelectedMaps(DomainTypeEnum.INPUT2, item.title,
          parentKey, "${item.key}_2", item.title, jznl_2,
          isShow: false);
    }
  }

  void _initData(List<BaseFilterItem> children) {
    children.forEach((item) {
      if (item.children.isNotEmpty && item.isSelected.value == true) {
        item.children.forEach((item) {
          String parentKey =
              logic.domainTitles[logic.selectedIndex.value].value.key;
          final maps = logic.filterPreviewVM.selectedMaps[parentKey];
          maps?.forEach((key, info) {
            if (key == "${item.key}_1") {
              logic.selectInputVM.getController("${item.key}_1").text =
                  info.value;
            } else if (key == "${item.key}_2") {
              logic.selectInputVM.getController("${item.key}_2").text =
                  info.value;
            }
          });
        });
      }
    });
  }

  _buildChildMChoiceWidget(BaseFilterItem data) {
    return Container(
      padding: const EdgeInsets.only(top: 10),
      child: Obx(() => Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Wrap(
                spacing: Constants.px_6,
                runSpacing: Constants.px_10,
                children: List.generate(data.children.length, (index) {
                  BaseFilterItem? item = data.children[index];
                  return ChoiceItemView(
                    text: item.key,
                    isSelected: item.isSelected.value,
                    onTap: () {
                      item.toggleSelection();
                      if (item.key == DisCons.NO_LIMIT) {
                        String parentKey = logic
                            .domainTitles[logic.selectedIndex.value].value.key;
                        logic.deleteSelectedMap(parentKey, child.key);
                        item.isSelected.value = true;
                        return;
                      } else {
                        for (var element in data.children) {
                          if (element.key == DisCons.NO_LIMIT) {
                            element.isSelected.value = false;
                          }
                        }
                        logic.addSelectMaps(
                            childKey: child.key,
                            sChoice: false,
                            isSelected: item.isSelected.value,
                            name: child.title,
                            key: item.key,
                            value: item.value);
                      }
                    },
                    selectedColor: Colors.red[50],
                    unselectedColor: JColor.color_f3f3f3,
                    borderColor: Colors.red[300],
                  );
                }),
              ),
            ],
          )),
    );
  }
}
